<!doctype html>
<html>

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title id='title'>Chat</title>
    <meta name="renderer" content="webkit">
    <script src="jq.js"></script>
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700,400italic">
    <script src="vuejs.js"></script>
    <link rel="stylesheet" href="amazeui.css">
    <link rel="stylesheet" href="masnn.css">
    <script src="https://masnn.gitee.io/chatter/layer/layer.js"></script>
    <link rel="stylesheet" href="highlight/styles/default.css">
    <script src="highlight/highlight.pack.js"></script>
    <script>hljs.initHighlightingOnLoad();</script>
    <script src="showdown/dist/showdown.min.js"></script>
    <script type="text/x-mathjax-config">
        MathJax.Hub.Config({
            jax: ["input/TeX", "output/HTML-CSS"],
            tex2jax: {
                inlineMath: [ ['$', '$'] ],
                displayMath: [ ['$$', '$$']],
                processEscapes: true,
                skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
            },
            messageStyle: "none",
            "HTML-CSS": { preferredFont: "TeX", availableFonts: ["STIX","TeX"] }
        });
    </script>
    <script src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
</head>

<body onunload="socket.send(JSON.stringify({code:'leave',nick:nick,data:nick+'离开了聊天'}));websocket.close();">
    <!--[if lte IE 9 ]>
    <div class="ie-warning"><button type="button">&times;</button>
    365 安全卫士提醒：你的浏览器太古董了，<a href="http://browsehappy.com/" target="_blank">速速点击换一个</a>！
   </div><![endif]-->
    <div id="app">
        <div class="masnn-bottom">
            <div v-if="enablepreview" id="preview"></div>
            <input type="text" id="ipt" class="am-form-field" style="width: 100%;" v-if="!multiline" v-model="value"
                oninput="setTimeout(prev,500);" placeholder="请输入：（支持Markdown与Mathjax）">
            <textarea type="text" id="ipt1" class="am-form-field" style="width: 100%;" v-if="multiline" v-model="value"
                oninput="setTimeout(prev,500);" placeholder="Input here:"></textarea>
            <label>
                <input type="checkbox" v-model="enablepreview"> 打开消息预览
            </label>
            <label>
                <input type="checkbox" v-model="shownicks"> 打开在线人数列表
            </label>
            <label>
                <input type="checkbox" v-model="multiline"> 插入多行文本
            </label>
            <button type="button" class="am-btn am-btn-primary masnn-right-1" @click="send();">发送</button>
            <button type="button" class="am-btn am-btn-default masnn-right" onclick="app.texts=[];">清屏</button>
        </div>
        <ul class="am-list" style="position: fixed; left:10px;height: 80%">
            <div v-for="i in texts">
                <li>
                    <p v-html="i.nick+':  '+i.data"></p>
                </li>
            </div>
        </ul>
        <div class="masnn-nicklist" v-if="shownicks">
            <ul class="am-list">
                <div v-for="i in nicks">
                    <li>
                        <p v-html="i"></p>
                    </li>
                </div>
            </ul>
        </div>
    </div>
    <script>
        wsurl = "ws://free.idcfengye.com:15442/";
        function main() {
            if (!window.WebSocket)
                layer.alert('Error:This browser does not supports WebSocket');
            var output;
            function getNick() {
                return prompt("输入昵称：");
            }
            app = new Vue({
                el: '#app',
                methods: {
                    send() {
                        if (this.value != '') {
                            socket.send(JSON.stringify({ code: "msg", nick: nick, data: HTMLEncode(this.value) }));
                            this.value = '';
                        }
                    }
                },
                data: { texts: [], value: '', enablepreview: false, shownicks: false, multiline: false, nicks: [] }
            })
            socket = new WebSocket(wsurl);
            socket.onopen = function (event) {
                layer.msg("正在连接到服务器，请稍侯...");
                if (typeof nick != "undefined") {
                    layer.msg("已重新连接");
                } else {
                    nick = getNick();
                    socket.send(JSON.stringify({ code: "join", nick: nick, data: nick + "加入了聊天" }));
                }
            };
            socket.onmessage = function (event) {
                var data = JSON.parse(event.data);
                console.log('Client received a message', data);
                if (data.code == "msg") {
                    var converter = new showdown.Converter();
                    data.data = converter.makeHtml(data.data);
                    app.texts.push(data);
                    setTimeout("MathJax.Hub.Queue(['Typeset',MathJax.Hub,'app']);dohighlight();", 200);
                    
                }
                if (data.code == "needpass")
                    socket.send(JSON.stringify({ code: "setpass", data: prompt("当前账户要求输入密码"), nick: nick }));
                if (data.code == "success")
                    layer.msg(data.data);
                if (data.code == 'fail')
                    layer.msg("错误：" + data.data)
                if (data.code == "join")
                    app.nicks.push(data.nick);
                if (data.code == "leave") {
                    var index = app.nicks.indexOf(data.nick)
                    app.nicks.splice(index, 1);
                }
            };
            socket.onclose = function (event) {
                console.log('Client notified socket has closed', event);
                layer.msg("已断开连接。暂不支持重新连接。请刷新页面");
            };
        };
        window.addEventListener("load", main(), false);
        $('#ipt').bind('keyup', function (event) {
            if (event.keyCode == "13") {
                app.send();
            }
        });
        function prev() {
            var converter = new showdown.Converter();
            $('#preview').html(converter.makeHtml(app.value));
            MathJax.Hub.Queue(['Typeset', MathJax.Hub, 'preview']);
            dohighlight();
        }
        function HTMLEncode(html) {
            var temp = document.createElement("div");
            (temp.textContent != null) ? (temp.textContent = html) : (temp.innerText = html);
            var output = temp.innerHTML;
            temp = null;
            return output;
        }
        function dohighlight() {
            $('pre code').each(function (i, block) {
                hljs.highlightBlock(block);
            });
        };
        setInterval("socket.send(JSON.stringify({code:'keep-alive',data:'',nick:nick}))", 10000);
    </script>
</body>
</html>